package com.landeb.shop.huo.frag;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.landeb.shop.R;
import com.landeb.shop.huo.Json2Act;
import com.landeb.shop.huo.MyApplication;


public class FocusFragment extends Fragment {
    private static final String BASE_URL = "baseUrl";

    private String mBaseUrl;

    private View mView;
    private WebView mWebView;
    private SwipeRefreshLayout mSRL;

    private String mUrlWithToken;
    private String token;
    private String mUrl = "http://www.landeb.com/index.php/Api/Url/go?url=find";

    public FocusFragment() {
        // Required empty public constructor
    }


    public static FocusFragment newInstance(String baseUrl) {
        FocusFragment fragment = new FocusFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_focus, container, false);


        initView();
        initData();
        initEvent();

        mWebView.loadUrl(mUrlWithToken);


        return mView;
    }

    private void initEvent() {
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setUserAgentString("android/app/landeb1.0");//添加UA,  “app/XXX”：是与h5商量好的标识，h5确认UA为app/XXX就认为该请求的终端为App

        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setLoadsImagesAutomatically(true);

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);

        saveData(mWebSettings);

        newWin(mWebSettings);

        mWebView.setWebChromeClient(webChromeClient);
        mWebView.setWebViewClient(webViewClient);


        Log.e("trueURL: ", mUrlWithToken);

//        js调用本地方法
        mWebView.addJavascriptInterface(this, "hook_app");

        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mWebView.loadUrl(mUrlWithToken);
                mSRL.setRefreshing(false);

            }
        });


    }

    private void initData() {


        SharedPreferences mPreferences = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        token = mPreferences.getString("token", "null");

        if (mUrl.startsWith("http://www.landeb.com/")) {

            mUrlWithToken = mUrl.contains("?") ? mUrl.concat("&token=" + token) : mUrl.concat("?token=" + token);

        } else {
            mUrlWithToken = mUrl;
        }

    }

    private void initView() {

        mWebView = (WebView) mView.findViewById(R.id.frag_focus_wv);

        mSRL = (SwipeRefreshLayout) mView.findViewById(R.id.frag_focus_srl);
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

    }


    /**
     * 多窗口的问题
     */
    private void newWin(WebSettings mWebSettings) {
        //html中的_bank标签就是新建窗口打开，有时会打不开，需要加以下
        //然后 复写 WebChromeClient的onCreateWindow方法
        mWebSettings.setSupportMultipleWindows(false);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    }

    /**
     * HTML5数据存储
     */
    private void saveData(WebSettings mWebSettings) {
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCachePath = getActivity().getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
    }

    WebViewClient webViewClient = new WebViewClient() {

        /**
         * 多页面在同一个WebView中打开，就是不新建activity或者调用系统浏览器打开
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl("javascript:o=document.createElement('script');o.src='" + MyApplication.BASE_DOMAIN + "/Public/js/hook.php';document.body.appendChild(o);");

            if (!TextUtils.isEmpty(view.getTitle())) {
//                mTitle.setText(view.getTitle());
            }
        }

    };

    WebChromeClient webChromeClient = new WebChromeClient() {

        //=========HTML5定位==========================================================
        //需要先加入权限
        //<uses-permission android:name="android.permission.INTERNET"/>
        //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
        //=========HTML5定位==========================================================

        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(view);
            resultMsg.sendToTarget();
            return true;
        }
        //=========多窗口的问题==========================================================

//        @Override
//        public void onPageFinished(WebView view, String url)
//        {
//            super.onPageFinished(view, url);
//            webview.loadUrl("javascript:o=document.createElement('script');o.src='http://www.123.456/789.js';document.body.appendChild(o);alert('aaaaa')");
//        }


        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);

//            finish();
        }
    };


    @Override
    public void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }


    //js调用的方法
    @JavascriptInterface
    public void run(String str) {
        Log.e("run: ", str);
//        Toast.makeText(this, S, Toast.LENGTH_SHORT).show();
        Json2Act.makeJson2Act(str, getActivity());
    }

}
